package com.tgpms.web.element.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.interfaces.dto.VformInterface;
import com.tgpms.util.Common;
import com.tgpms.util.VformBeanUtil;
import com.tgpms.web.element.dao.WsElementMapper;
import com.tgpms.web.element.dto.ElementDto;
import com.tgpms.web.element.entity.WsElement;
import com.tgpms.web.element.service.IWsElementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 物资设备属性从表 服务实现类
 * </p>
 *
 * @author jl
 * @since 2020-07-07
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public class WsElementServiceImpl extends ServiceImpl<WsElementMapper, WsElement> implements IWsElementService {

    @Resource
    private WsElementMapper mapper;
    @Autowired
    private VformInterface vformInterface;

    /**
     * 新增物资设备属性从表
     */
    @Override
    public Result addWsElement(WsElement en, Result result) {
    	String findjson = "{\"COMMODITY_NUMBER=\":\""+en.getCommodityNumber()+"\",\"WSE_CODE\":\""+en.getWseCode()+"\"}";
    	Result findReslut = vformInterface.find("D1127", findjson, "1", "100", "N", "N", "");
    	System.out.println("vform查询返回结果为:  "+findReslut);
    	if(findReslut==null || !findReslut.getSuccess()) {
    		result.setSuccess(false);
    		result.setMsg(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
			return result;
		}
		if(findReslut.getData().toString().equals("{\"message\":\"login\"}")) {
			result.setSuccess(false);
    		result.setMsg(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
			return result;
		}
		if(findReslut.getData().toString().equals("[]")) {
			en.setInsertDate(new Date());
			//对象转json字符串, 字段驼峰转下划线大写字段
			JSONObject json = VformBeanUtil.entityToJsonString(en);
			if(json==null || json.isEmpty()) {
				result.setSuccess(false);
	    		result.setMsg(ExceptionExplain.ERROR_BY_PARSING.getExplain());
				return result;
			}
			//vform同步插入
			Result res = vformInterface.insert("D1127", json);
			System.out.println("vform增加返回结果   "+res);
			if(result==null || !result.getSuccess()) {
				result.setSuccess(false);
	    		result.setMsg(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
				return result;
			}
			String resData = res.getData().toString();
			if(resData.equals("{\"message\":\"login\"}")) {
				result.setSuccess(false);
	    		result.setMsg(ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
				return result;
			}
			JSONObject reJson = JSONObject.parseObject(resData);
			if(reJson.get("status").toString().equals("error")) {
				result.setSuccess(false);
	    		result.setMsg(reJson.get("validateError").toString());
				return result;
			}else {
				result.setSuccess(true);
	    		result.setMsg(ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
				return result;
			}
		}else {
			result.setSuccess(false);
    		result.setMsg(ExceptionExplain.ERROR_BY_INSERT_REPETITION.getExplain());
			return result;
		}
    }

    /**
     * 更新物资设备属性从表
     */
    @Override
    public Result updateWsElement(WsElement en, Result result) {
    	en.setModifyDate(new Date());
		JSONObject keyjson = new JSONObject();
		keyjson.put("COMMODITY_NUMBER", en.getCommodityNumber());
		keyjson.put("WSE_CODE", en.getWseCode());
		JSONObject pajson = new JSONObject();
		pajson = VformBeanUtil.entityToJsonStringByUpdate(en);
		pajson.remove("COMMODITY_NUMBER");
		pajson.remove("WSE_CODE");

		System.out.println("vform更新上送主键   "+keyjson.toString());
		System.out.println("vform更新上送参数   "+pajson.toString());
		//vform同步更新
		Result res = vformInterface.update("D1127", keyjson.toString(),pajson.toString(),"Y","Y",en.getDataOwner());
		System.out.println("vform更新返回结果   "+res);
		if(res==null || !res.getSuccess()) {
			result.setSuccess(false);
    		result.setMsg(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
			return result;
		}
		String resData = res.getData().toString();
		JSONObject reJson = JSONObject.parseObject(resData);
		if(reJson.get("status").toString().equals("error")) {
			result.setSuccess(false);
    		result.setMsg(reJson.get("validateError").toString());
			return result;
		}else {
			result.setSuccess(true);
    		result.setMsg(ExceptionExplain.SUCCESS_BY_UPDATE.getExplain());
			return result;
		}
    }

    /**
     * 根据主键删除物资设备属性从表
     */
    @Override
    public Result deleteWsElement(String commodityNumber,String wseCode, Result result) {
    	JSONObject keyjson = new JSONObject();
    	keyjson.put("COMMODITY_NUMBER", commodityNumber);
		keyjson.put("WSE_CODE", wseCode);
		System.out.println("vform删除上送主键   "+keyjson.toString());
		//vform同步删除
		Result res = vformInterface.delete("D1127", keyjson.toJSONString());
		System.out.println("vform删除返回结果   "+res);
		if(res==null || !res.getSuccess()) {
			result.setSuccess(false);
    		result.setMsg(ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
			return result;
		}
		String resData = res.getData().toString();
		JSONObject reJson = JSONObject.parseObject(resData);
		if(reJson.get("status").toString().equals("error")) {
			result.setSuccess(false);
    		result.setMsg(reJson.get("validateError").toString());
			return result;
		}else {
			result.setSuccess(true);
    		result.setMsg(ExceptionExplain.SUCCESS_BY_DELETE.getExplain());
			return result;
		}
    }

    @Override
    public Map<String, String> batchImport(MultipartFile file, String type, String dataOwner, String insertName) throws IOException {
        Map<String, String> map = new HashMap<>();

        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        List<ElementDto> all = reader.readAll(ElementDto.class);
        List<WsElement> collect = all.stream().map(e -> {
            WsElement wsElement = new WsElement();
            wsElement.setCommodityNumber(e.getSUPPLIES_CODE());
            wsElement.setWseCode(e.getCODE());
            wsElement.setAcceptElement(e.getACCEPT_ELEMENT());
            wsElement.setInspectionMethod(e.getINSPECTION_METHOD());
            wsElement.setRequestSource(e.getREQUEST_SOURCE());

            wsElement.setInsertUser(insertName);
            wsElement.setInsertDate(new Date());
            if (StrUtil.isNotBlank(dataOwner)) {
                wsElement.setDataOwner(dataOwner);
            }
            return wsElement;
        }).collect(Collectors.toList());

        collect.forEach(e -> {
        	addWsElement(e, new Result());
        });
        map.put("code", "1");
        map.put("info", ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
        map.put("data", "批量数据新增成功");
        return map;
    }

}
